import com.im30.jenkins.pipeline.utils.BuildConfig

def call() {
    // This limits build concurrency to 1 per branch
    properties([
            disableConcurrentBuilds(),
            buildDiscarder(logRotator(artifactDaysToim30Str: '', artifactNumToim30Str: '', daysToim30Str: '7', numToim30Str: '50'))
    ])

    dockerNode.javaBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        try {
            stage('Preparation') {
                echo "remote config ${scm.userRemoteConfigs}"
                try {
                    // 通知 banana
                    def scmUrl = scm.userRemoteConfigs[0].getUrl()
                    status = sh(script: "curl https://banana.sre.gotoim30.com/builds/syncGit?repo=$scmUrl", returnStatus: true)
                    echo status
                } catch (err) {
                    echo err.message
                }

                // fetch remote tags
                checkout scm: [
                        $class                           : 'GitSCM',
                        branches                         : scm.branches,
                        doGenerateSubmoduleConfigurations: scm.doGenerateSubmoduleConfigurations,
                        extensions                       : [[$class: 'CloneOption', noTags: false, shallow: false, depth: 0, reference: '']],
                        userRemoteConfigs                : scm.userRemoteConfigs
                ]
            }

            stage('Test') {
                mavenUtil.unittest()
                try {
                    mavenUtil.report()
                } catch (err) {
                    // ignore No test report files were found error
                    echo err.getMessage()
                }
            }
            stage('Pmd') {
                try {
                    mavenUtil.pmd()
                } catch (err) {
                    // ignore pmd run failed error
                    echo err.getMessage()
                }
            }
            stage('Sonar') {
                try {
                    mavenUtil.sonar()
                } catch (err) {
                    // ignore pmd run failed error
                    echo err.getMessage()
                }
            }
            stage('Dependencies') {
                try {
                    mavenUtil.dependencies()
                } catch (err) {
                    echo err.getMessage()
                }
                try {
                    String branch = jobUtil.getBranchName()
                    mavenUtil.snapshotCheck(branch)
                } catch(err) {
                    echo err.getMessage()
                    String url = "https://open.feishu.cn/open-apis/bot/v2/hook/112510b3-9588-4935-826d-43508eb60442"
                    notifyUtil.notifyText(url, "SNAPSHOT 检测失败", "${env.BUILD_URL}\\n${e.message}")
                }
            }

            stage('Security Scan') {
                parallel (
                        "murphyScan": {
                            stage('murphyScan') {
                                try {
                                    securityUtil.murphyScan(mavenUtil.getProjectName())
                                } catch (err) {
                                    echo err.getMessage()
                                }
                            }
                        },
                        "fortify-sca": {
                            stage('fortify-sca') {
                                try {
                                    securityUtil.fortifySca()
                                } catch (err) {
                                    echo err.getMessage()
                                }
                            }
                        }
                )
            }

            buildConfig = BuildConfig.load(this)
            if (buildConfig == null) {
                throw new Exception("Cannot parse build.yaml")
            }

            stage('Build') {
                if (buildConfig.isLibRepo()) {
                    echo 'Deploy to Maven'
                    mavenUtil.deployMaven(buildConfig)
                }

                if (buildConfig.isAppRepo()) {
                    echo 'Build JAR and DockerImage'
                    jobUtil.buildApps(buildConfig)
                }
            }

        } finally {
            isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
            if (buildConfig != null) {
                notifyUtil.notifyRepo(buildConfig.getNotifyConfig(), jobUtil.getRepoName(), jobUtil.getBranchName(), isSuccess)
            }
        }
    }
}